
/* Includes ------------------------------------------------------------------*/
#include "bh1750.h"
#include "i2c-eiri.h"
#include "usart.h"
#include "string.h"

BH1750_MODE mode2 = BH1750_REGISTER_PO;

uint8_t I2C_BH1750_ReadData(uint16_t Addr, uint8_t Reg, uint8_t* data, uint8_t size)
{    
    while(HAL_I2C_Master_Transmit(&hi2c1, Addr<<1, &Reg, 1, 100) != HAL_OK)
    {                
        if (HAL_I2C_GetError(&hi2c1) != HAL_I2C_ERROR_AF)
        {
            I2C1_ClearBusyFlag();
            SET_BH1750_OperModeOH();
            DEBUG_Printf("ERROR:%d\r\n",HAL_I2C_GetError(&hi2c1));
            DEBUG_Printf("i2c1.instance->sr2:%x\r\n",hi2c1.Instance->SR2);
            DEBUG_Printf("read transmit anknowledgement failure\r\n");
        }
    }
    
    if(HAL_I2C_Master_Receive(&hi2c1, (Addr<<1)|0x01, data, size, 100) != HAL_OK)
    {
        if (HAL_I2C_GetError(&hi2c1) != HAL_I2C_ERROR_AF)
        {
            I2C1_ClearBusyFlag();
            SET_BH1750_OperModeOH();
            DEBUG_Printf("ERROR:%d\r\n",HAL_I2C_GetError(&hi2c1));
            DEBUG_Printf("i2c1.instance->sr2:%x\r\n",hi2c1.Instance->SR2);
            DEBUG_Printf("read receive anknowledgement failure\r\n");
        }        
    }         
    return 0;
}

uint8_t I2C_BH1750_WriteData(uint16_t Addr, uint8_t Reg, uint8_t* data, uint8_t size)
{       
    uint8_t pData[size+1];
    pData[0] = Reg;
    memcpy(&pData[1], data, size);  
    
    while(HAL_I2C_Master_Transmit(&hi2c1, Addr<<1, pData, size + 1, 500) != HAL_OK)
    {                
        //if (HAL_I2C_GetError(&hi2c1) != HAL_I2C_ERROR_AF )
        {
            I2C1_ClearBusyFlag();
            SET_BH1750_OperModeOH();
            DEBUG_Printf("ERROR:%d\r\n",HAL_I2C_GetError(&hi2c1));
            DEBUG_Printf("i2c1.instance->sr2:%x\r\n",hi2c1.Instance->SR2);
            DEBUG_Printf("write transmit anknowledgement failure\r\n");
            //HAL_Delay(1000);
        }        
    }      
    return 0;
}


uint8_t SET_BH1750_OperModeOH(void)
{
    //mode2 = BH1750_REGISTER_OH;
    //I2C_BH1750_WriteData(BH1750_ADDRESS, BH1750_REGISTER_OH, (uint8_t*)&mode2, 1);
    return 1;
}

uint16_t GET_BH1750_GuangZhao(void)
{
    uint16_t temp,value = 0;
    I2C_BH1750_ReadData(BH1750_ADDRESS, BH1750_REGISTER_OH, (uint8_t*)&temp, 2);
    value |= (temp & 0xFF00) >> 8;
    value |= (temp & 0xFF) << 8;
    return value;
}


